import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import {
  AfterViewInit,
  Directive,
  DoCheck,
  ElementRef,
  forwardRef,
  HostListener,
  Input,
  KeyValueDiffer,
  KeyValueDiffers,
  OnInit,
} from '@angular/core';
import { InputHandler } from './currency.handler';

export const CURRENCYMASKDIRECTIVE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CurrencyDirective),
  multi: true,
};

@Directive({
  selector: '[appCurrency]',
  providers: [CURRENCYMASKDIRECTIVE_VALUE_ACCESSOR],
})
export class CurrencyDirective implements AfterViewInit, ControlValueAccessor, DoCheck, OnInit {
  // 输入属性
  @Input() options: any = {};

  // 内部属性
  inputHandler: InputHandler;
  keyValueDiffer: KeyValueDiffer<any, any>;

  optionsTemplate = {
    align: 'right',
    allowNegative: true,
    decimal: '.',
    precision: 2,
    prefix: '$ ',
    suffix: '',
    thousands: ',',
  };

  //
  constructor(private elementRef: ElementRef, private keyValueDiffers: KeyValueDiffers) {}

  ngAfterViewInit() {}

  ngOnInit() {
    this.inputHandler = new InputHandler(this.elementRef.nativeElement, (<any>Object).assign({}, this.optionsTemplate, this.options));
  }

  ngDoCheck() {}

  // =============双向绑定===================
  registerOnChange(callbackFunction: Function) {
    this.inputHandler.setOnModelChange(callbackFunction);
  }
  registerOnTouched(callbackFunction: Function): void {
    this.inputHandler.setOnModelTouched(callbackFunction);
  }

  writeValue(value: any) {}
  // =================================
  // 输入事件监听
  @HostListener('compositionend', ['$event'])
  onCompositionEnd(event: any) {
    if (!this.isChromeAndroid()) {
      this.inputHandler.handleCompositionEnd();
    }
  }
  @HostListener('keydown', ['$event'])
  handleKeydown(e: any) {
    console.log('keydown');
    if (!this.isChromeAndroid()) {
      this.inputHandler.handleKeydown(e);
    }
  }

  @HostListener('keypress', ['$event'])
  handleKeypress(event: any) {
    console.log('keypress');
    if (!this.isChromeAndroid()) {
      this.inputHandler.handleKeypress(event);
    }
  }
  //
  // @HostListener('keyup', ['$event'])
  // handleKeyup(event: any) {
  //   console.log('keyup');
  //   if (!this.isChromeAndroid()) {
  //     // this.inputHandler.handleKeyup(event);
  //   }
  // }

  isChromeAndroid(): boolean {
    return /chrome/i.test(navigator.userAgent) && /android/i.test(navigator.userAgent);
  }
}
